package com.dc.sr.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.UUID;

/**
 * 使用redis lua脚本实现分布式锁
 * 本质还是通过setnx指令
 *
 * @author duchao
 */
@Component
public class RedisLuaLock {

    private final static DefaultRedisScript<Long> LOCK_LUA_SCRIPT = new DefaultRedisScript<>(
            "if redis.call('setnx',KEYS[1],ARGV[1]) == 1 then return redis.call('expire',KEYS[1],ARGV[2])  else return 0 end"
            , Long.class
    );

    private final static DefaultRedisScript<Long> UNLOCK_LUA_SCRIPT = new DefaultRedisScript<>(
            "if redis.call('EXISTS',KEYS[1]) == 1 then return redis.call('del',KEYS[1]) else return 0 end"
            , Long.class
    );

    private final StringRedisTemplate redisTemplate;

    public RedisLuaLock(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 加锁
     *
     * @param key           键
     * @param timeInSeconds 过期时间
     * @return
     */
    public boolean lock(final String key, long timeInSeconds) {
        Object value = System.currentTimeMillis();
        Long result = redisTemplate.execute(LOCK_LUA_SCRIPT, Arrays.asList(key), value, String.valueOf(timeInSeconds));
        return result == 1;
    }

    /**
     * 释放锁
     *
     * @param key 键
     * @return
     */
    public boolean unlock(String key) {
        Long result = redisTemplate.execute(UNLOCK_LUA_SCRIPT, Arrays.asList(key));
        return result != null && result == 1;
    }
}
